package org.example.big_event.controller;

import org.example.big_event.pojo.Category;
import org.example.big_event.pojo.Result;
import org.example.big_event.service.CategoryService;
import org.example.big_event.service.CategoryServiceimpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.PrivateKey;
import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public Result add(@RequestBody @Validated(Category.Add.class) Category category) {
        categoryService.add(category);
        return Result.success();
    }
    @GetMapping
    public Result<List<Category>> list(){
        List<Category> cs = categoryService.list();
        return Result.success(cs);
    }

    @GetMapping("/detail")
    public Result<Category> detail(Integer id){
        Category c = categoryService.findByCategoryId(id);
        //校验文章分类是否存在
        if (c!=null){
            return Result.success(c);
        }
        else  {
            return Result.error("文章分类不存在");
        }

    }
    @PutMapping
    public Result update(@RequestBody @Validated(Category.Update.class) Category category) {
        Integer id = category.getId();
        Category c = categoryService.findByCategoryId(id);
        if (c!=null) {
            categoryService.update(category);
            return Result.success();
        }
        else {
            return Result.error("文章分类不存在");
        }
    }
    @DeleteMapping
    public Result delete(Integer id){
        Category c = categoryService.findByCategoryId(id);
        //校验文章分类是否存在
        if (c!=null){
            categoryService.delete(id);
            return Result.success();
        }
        else  {
            return Result.error("文章分类不存在");
        }
    }
}
